package com.ai.trickycards.ui.activity

import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.ai.trickycards.Constant
import com.ai.trickycards.R
import com.ai.trickycards.ui.adapter.BaseRecyclerAdapter
import com.ai.trickycards.ui.adapter.BaseViewHolder
import com.ai.trickycards.databinding.ActivityGuideBinding
import com.ai.trickycards.databinding.AdapterGuideItemBinding
import com.ai.trickycards.utils.SP
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class GuideActivity : BaseActivity() {

    private val binding by lazy {
        ActivityGuideBinding.inflate(layoutInflater)
    }

    private var autoScrollJob: Job? = null
    private var isTouchScreen = false
    private var isSpeakFinish = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setWindowInsets(binding.root, insetBottom = false)
        binding.ivClose.setOnClickListener { v ->
            if (binding.viewPager.currentItem - 1 == binding.viewPager.adapter?.itemCount) {
                down(v)
            } else {
                skip(v)
            }
        }

        val pages = listOf(
            R.mipmap.guide01,
            R.mipmap.guide02,
            R.mipmap.guide03,
            R.mipmap.guide04,
            R.mipmap.guide05
        )

        val chats = listOf(
            listOf("Trickycards is a game for 4 to 6 players where the objective is to guess how many cards of a specified value are on the table to determine the winner. Each player randomly draws cards from a designated range within a complete deck, and only the player knows their own cards. At the start of each round, all players have the same amount of health points."),
            listOf(
                "During a player's turn, they have three options:",
                " · Raise: Guess a higher number of cards or a higher card value.",
                " · Doubt: Challenge the previous player's guess, and all players reveal their cards.",
                " · Calzo: Fully confirm the previous player's guess, and all players reveal their cards."
            ),
            listOf("When a player chooses Doubt, all players reveal their cards to verify the guess on the table. If the total number of cards matching the guessed type on the table is less than the guessed amount, the player who doubted wins and gains 1 life, while the previous player loses 1 life. If the total is equal to or greater than the guessed amount, the player who doubted loses."),
            listOf("When a player chooses Calzo, all players reveal their cards to verify the guess on the table. If the total number of cards matching the guessed type on the table exactly equals the guessed amount, the player who called Calzo wins and gains 2 life. If the total is not equal to the guessed amount, the player who called Calzo loses and loses 2 life."),
            listOf("When a player's life reach 0, the game ends. The player with the most lifes wins the game, while players with 0 life lose. lifes are only valid for the current round of the game."),

            )
        binding.viewPager.adapter = object : BaseRecyclerAdapter(R.layout.adapter_guide_item) {
            override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
                val binding = AdapterGuideItemBinding.bind(holder.itemView)
                binding.ivImg.setImageResource(pages[position])
            }

            override fun getItemCount(): Int {
                return pages.size
            }
        }
        binding.dotsIndicator.attachTo(binding.viewPager)

        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.chatView.reset()
                isSpeakFinish = false
                binding.chatView.startSpeak(chats[position], speed = 20) {
                    isSpeakFinish = true
                    setButton(position)
                }
            }
        })

        binding.root.onTouchListener = { event ->
            if (event?.action == MotionEvent.ACTION_DOWN) {
                isTouchScreen = true
                autoScrollJob?.cancel()
            } else if (event?.action == MotionEvent.ACTION_UP
                || event?.action == MotionEvent.ACTION_CANCEL
            ) {
                isTouchScreen = false
                if (isSpeakFinish) {
                    autoScroll()
                }
            }
        }

        onBackPressedDispatcher.addCallback(this, true) {

        }
    }

    private fun setButton(position: Int) {
        if (position + 1 == binding.viewPager.adapter?.itemCount) {
            binding.chatView.setRightOption("Down", ::down)
        } else {
            binding.chatView.setLeftOption("Skip", ::skip)
            binding.chatView.setRightOption("Next", ::next)
            autoScroll()
        }
    }

    private fun skip(v: View?) {
        SP.putBoolean(this, Constant.SP_KEY.GUIDE_SHOWED, true)
        finish(RESULT_CANCELED)
    }

    private fun next(v: View?) {
        binding.viewPager.currentItem += 1
    }

    private fun down(v: View?) {
        SP.putBoolean(this, Constant.SP_KEY.GUIDE_SHOWED, true)
        finish(RESULT_OK)
    }

    private fun autoScroll() {
        autoScrollJob?.cancel()
        autoScrollJob = lifecycleScope.launch {
            delay(5000)
            next(null)
            autoScrollJob = null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.chatView.stopSpeak()
        autoScrollJob?.cancel()
    }
}